﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections;
using hnrzxt.tool;
using System.Text;
using Nancy;
using System.Web.Http.Controllers;
using dingdingsuccess;
using System.Diagnostics;
using AlibabaCloud.SDK;
using Microsoft.AspNetCore.Mvc.RazorPages;
using AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models;
using static AlibabaCloud.SDK.Dingtalkworkflow_1_0.Models.GetProcessInstanceResponseBody.GetProcessInstanceResponseBodyResult.GetProcessInstanceResponseBodyResultOperationRecords;
using System.Net;
using hnrzxt.data;

namespace hnrzxt.API
{
    [Route("api/[controller]")]
    [ApiController]
    public class getCalBack : ControllerBase
    {
        private readonly ApplicationDbContext _db;
        public getCalBack(ApplicationDbContext db)
        {
            _db = db;
        }
        [HttpPost("/callback")]

        public DingDingBackEntity dingding(string signature, string timestamp, string nonce, [FromBody] Dingencrypt encrypt)
        {
            var encryptStr = encrypt.encrypt;
            //实例化钉钉解密类构造参数为对应的 应用中的token、aes_key、AppKey值
            DingTalkEncryptor dingTalkEncryptor = new("hAOOGEvMnbIGChTm", "FjnUwqqokwtnTC531hBwPpCBkYCSv2msGABAn60Ws5e", "dinghogrbpkcvz7nblnn");
            //定义字符串接收解密后的值
            string text = dingTalkEncryptor.getDecryptMsg(signature, timestamp, nonce, encryptStr);

            JToken jToken = JToken.Parse(text);
            //取出事件类型字段
            string EventType = jToken["EventType"].ToString();

            PubFunc pubFunc = new(_db);

            //第二部分
            //  { //判断事件类型是否是日程事件
            switch (EventType)
            {
                case "check_url":
                    PubFunc.WriteLog(DateTime.Now + "测试回调的的正确性", "Log", true);
                    break;
                case "bpms_task_change":
                    //审批任务开始、结束、转交。                  
                    PubFunc.WriteLog(DateTime.Now + "审批任务开始、结束、转交。 type:" + jToken["EventType"].ToString() + " " + jToken["title"].ToString(), "Log", true);
                    break;
                case "bpms_instance_change":
                    #region 审批实例
                    //{审批实例结束|终止
                    //    "EventType": "bpms_instance_change",
                    //    "processInstanceId": "ad253df6-e175caf-xxxxxxxxxxxx", //审批实例id。
                    //    "finishTime": 1495592305000,
                    //    "corpId": "dinge8a56572f80b02a8ffexxxx",
                    //    "title": "自测-1016",
                    //    "type": "finish", //finish：审批正常结束（同意或拒绝）; terminate：审批终止（发起人撤销审批单）
                    //    "url": "https://aflow.dingtalk.com/dingtalk/mobile/homepage.htm?corpid=ding2c015874d817xxxx&dd_share=",
                    //    "result": "refuse",   //正常结束时result为agree，拒绝时result为refuse，审批终止时没这个值。
                    //    "createTime": 1495592272000,
                    //    "staffId": "manager75",//发起审批实例的员工。
                    //    "processCode":"Pro-xxx" //审批模板的唯一码。
                    //  }
                    #endregion
                    //人事相关流程
                    //1.员工档案基本信息
                    PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + "  processCode:" + jToken["processCode"].ToString()+ "  processInstanceId:" + jToken["processInstanceId"], "Log", true);
                    //入职信息登记表
                    if (jToken["processCode"].ToString() == "PROC-5343A518-82D9-4934-8621-899AD67F4FD9")//流程模板id
                    {
                        if (jToken["type"].ToString() == "finish" & jToken["result"].ToString() == "agree")
                        {
                            PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);
                            //同步到人事系统
                            PubFunc p = new(_db);
                            p.DataToHR(jToken["processInstanceId"].ToString());

                            p.FiletoHr(jToken["processInstanceId"].ToString());
                        }
                    }
                    //录用审批
                    else if (jToken["processCode"].ToString() == "PROC-33B8854A-595C-4059-A662-D0730A9E9ADD")
                    {
                        if (jToken["type"].ToString() == "finish" & jToken["result"].ToString() == "agree")
                        {
                            PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);
                            PubFunc pub = new(_db);
                            pub.AddZLinfo(jToken["processInstanceId"].ToString());
                            pub.FiletoHr(jToken["processInstanceId"].ToString());
                        }

                    }
                    //离职审批
                    else if (jToken["processCode"].ToString() == "PROC-DEB8B07C-BBAE-4079-B280-40582EEBF232")
                    {
                        if (jToken["type"].ToString() == "finish" & jToken["result"].ToString() == "agree")
                        {
                            PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);
                            PubFunc pub = new(_db);
                            pub.Leave(jToken["processInstanceId"].ToString());
                        }
                    }
                    //合同审批
                    else if (jToken["processCode"].ToString() == "PROC-C8E3746F-C472-42E5-AF70-60FB2832329F")
                    {
                        if (jToken["type"].ToString() == "finish" & jToken["result"].ToString() == "agree")
                        {
                            PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);
                            PubFunc pub = new(_db);
                            pub.Sign(jToken["processInstanceId"].ToString());
                        }
                    }
                    //转正审批PROC-C7901724-38D0-4266-B6D9-6B050034AE0B
                    else if (jToken["processCode"].ToString() == "PROC-C7901724-38D0-4266-B6D9-6B050034AE0B")
                    {
                        if (jToken["type"].ToString() == "finish" & jToken["result"].ToString() == "agree")
                        {
                            PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);
                            PubFunc pub = new(_db);
                            pub.ZhuanZ(jToken["processInstanceId"].ToString());
                        }
                    }
                    else if (jToken["processCode"].ToString()== "PROC-221064EA-043D-4902-837B-04CD0511CF42")
                    {
                        PubFunc.WriteLog(DateTime.Now + " " + jToken["title"].ToString() + " 审批实例id:" + jToken["processInstanceId"].ToString(), "Log", true);

                    }
                    break;
                case "org_dept_modify":
                   PubFunc.WriteLog(DateTime.Now + jToken["DeptId"].ToString(), "Log_dept", true);
                    var a = jToken["DeptId"].ToString().Replace("[", "").Replace("]", "").Trim();
                    var b = long.Parse(a);
                    PubFunc.WriteLog(DateTime.Now + " sting:" + a + " long:" + b, "Deptid", true);
                    pubFunc.UpDeptToHR(b, HNWZ_API.Token());
                    break;
                case "org_dept_create":
                    //通讯录企业部门修改。
                   PubFunc.WriteLog(DateTime.Now + "通讯录企业部门"+ jToken["DeptId"].ToString() + "添加", "Log_dept", true);
                    var c = jToken["DeptId"].ToString().Replace("[", "").Replace("]", "").Trim();
                    var d = long.Parse(c);
                    PubFunc.WriteLog(DateTime.Now + " sting:" + c + " long:" + d, "Deptid", true);
                    pubFunc.CreateDeptToHR(d, HNWZ_API.Token());
                    break;
                case "org_dept_remove":
                    //通讯录企业部门删除。
                   PubFunc.WriteLog(DateTime.Now + "通讯录企业部门修改", "Log_dept", true);
                    var e = jToken["DeptId"].ToString().Replace("[", "").Replace("]", "").Trim();
                    var f = long.Parse(e);
                    PubFunc.WriteLog(DateTime.Now + " sting:" + e + " long:" + f, "Deptid", true);
                    pubFunc.DeleteDeptToHR(f);
                    break;

                default:
                    break;
            }

            //第三部分
            #region 返回加密字符串
            var msg = dingTalkEncryptor.getEncryptedMap("success");
            DingDingBackEntity back = new DingDingBackEntity();
            back.msg_signature = msg["msg_signature"];
            back.encrypt = msg["encrypt"];
            back.timeStamp = msg["timeStamp"];
            back.nonce = msg["nonce"];
            return back;
            
            string result = JsonConvert.SerializeObject(back);
            PubFunc.WriteLog(DateTime.Now + " 返回的信息：\r\n" + result, "Log", true);
            #endregion
        }
    }
}
